package com.caishi.lkx.user.excelListener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.caishi.lkx.user.mapper.DepartmentMapper;
import com.caishi.lkx.user.model.DepartmentModel;
import com.caishi.lkx.user.vo.DepartmentImportVo;
import com.zzw.common.Wrappers;
import com.zzw.common.exception.BizRuntimeException;
import jodd.util.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author huangpeng
 * @Description
 * @Date 2022/6/2 16:13
 **/
public class ImportDepartmentListener implements ReadListener<DepartmentImportVo> {
    final List<DepartmentImportVo> list = new ArrayList<>();
    final Map<String, String> failMap = new ConcurrentHashMap<>();
    private final String createdBy;
    private final DepartmentMapper departmentMapper;
    private final Long groupId;
    public ImportDepartmentListener(String createdBy, DepartmentMapper departmentMapper,Long groupId) {
        this.createdBy = createdBy;
        this.departmentMapper = departmentMapper;
        this.groupId=groupId;
    }

    @Override
    public void invoke(DepartmentImportVo departmentImportVo, AnalysisContext analysisContext) {
        if(StringUtil.isBlank(departmentImportVo.getName())){
            throw new BizRuntimeException("导入失败,检查文件格式" );
        }
        list.add(departmentImportVo);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (CollUtil.isNotEmpty(list)) {
            list.parallelStream().forEach(vo -> {
                    DepartmentModel model = new DepartmentModel();
                    model.setName(vo.getName());
                    model.setGroupId(groupId);
                    model.setCreatedBy(createdBy);
                    if(StrUtil.isNotBlank(vo.getPid())){
                        DepartmentModel one = departmentMapper.selectOne(Wrappers.<DepartmentModel>lambdaQuery().eq(DepartmentModel::getId, vo.getPid()).eq(DepartmentModel::getGroupId, groupId));
                        if(null==one){
                            failMap.put(vo.getName(),"上级部门id未存在");
                            return;
                        }else{
                            model.setParentId(one.getId());
                        }
                    }
                    departmentMapper.insert(model);
            });

        }
        if (!failMap.isEmpty()) {
            throw new BizRuntimeException("导入失败:" + failMap);
        }
    }
}
